<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名称" prop="resName">
        <el-input
          v-model="queryParams.resName"
          placeholder="请输入文件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科目" prop="resType">
        <el-select v-model="queryParams.resType" placeholder="请选择科目" clearable filterable>
          <el-option
            v-for="dict in dict.type.t_subject"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上传人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入上传人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:resources:add']"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="resourcesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="文件名称" align="center" prop="resName"/>
      <el-table-column label="科目" align="center" prop="resType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.t_subject" :value="scope.row.resType"/>
        </template>
      </el-table-column>
      <el-table-column label="文件说明" align="center" prop="resRemake"/>
      <el-table-column label="文件大小" align="center" prop="resSize">
        <template slot-scope="scope">
          <span>{{ scope.row.resSize | filterType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下载量" align="center" prop="resDownloadCount" sortable/>
      <el-table-column label="上传人" align="center" prop="createBy"/>
      <el-table-column label="上传时间" align="center" prop="createTime" :formatter="dateFormat" sortable/>
      <el-table-column label="审核状态" align="center" prop="resState" sortable>
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.resState === 0 ? 'primary' :scope.row.resState==1?'success': 'danger'"
            disable-transitions>{{ scope.row.resState === 0 ? '待审核' : scope.row.resState == 1 ? '通过' : "未通过" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:resources:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
          >下载
          </el-button>
          <el-popconfirm
            confirm-button-text='通过'
            cancel-button-text='不通过'
            icon="el-icon-info"
            icon-color="red"
            @confirm="handleAudit(1,scope.row)"
            @cancel="handleAudit(2,scope.row)"
            title="这是一段内容确定删除吗？"
          >
            <el-button
              size="mini"
              type="text"
              slot="reference"
              icon="el-icon-user"
              v-hasPermi="['business:resources:remove']"
              v-if="scope.row.resState==0"
            >审核
            </el-button>
          </el-popconfirm>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:resources:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学习文件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件名称" prop="resName">
          <el-input v-model="form.resName" placeholder="请输入文件名称"/>
        </el-form-item>
        <el-form-item label="科目" prop="resType">
          <el-select v-model="form.resType" placeholder="请选择科目" filterable>
            <el-option
              v-for="dict in dict.type.t_subject"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件说明" prop="resRemake">
          <el-input type="textarea" v-model="form.resRemake" placeholder="请输入文件说明"/>
        </el-form-item>
        <el-form-item label="上传文件" prop="resSize">
          <el-upload
            ref="upload"
            :limit="1"
            accept=".doc,.docx,.xls,.xlsx,.pdf,.ppt,.txt,.pptx,.rar,.zip,.7z,.jpg,.gif,.jpeg,.png,.mp4,.avi,.rmvb"
            :action="upload.url"
            :headers="upload.headers"
            :file-list="upload.fileList"
            :on-exceed="handleExceed"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :before-remove="beforeRemove"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <!--            <el-button style="margin-left: 10px;" size="small" type="success" :loading="upload.isUploading"-->
            <!--                       @click="submitUpload">上传到服务器-->
            <!--            </el-button>-->
            <div slot="tip" class="el-upload__tip">
              可上传.doc,.docx,.xls,.xlsx,.pdf,.ppt,.txt,.pptx,.rar,.zip,.7z,.jpg,.gif,.jpeg,.png,.mp4,.avi,.rmvb格式文件，且不超过500M
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listResources,
  getResources,
  delResources,
  addResources,
  updateResources,
  downLoadFile
} from "@/api/business/resources";
import {getToken} from "@/utils/auth";

export default {
  name: "Resources",
  dicts: ['t_subject'],
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学习文件表格数据
      resourcesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        resName: null,
        resType: null,
        resFormat: null,
        resRemake: null,
        resSize: null,
        resDownloadCount: null,
        createBy: null,
        createTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          {required: true, message: "$comment不能为空", trigger: "blur"}
        ],
        resName: [
          {required: true, message: "文件名称不能为空", trigger: "blur"}
        ],
        resType: [
          {required: true, message: "科目不能为空", trigger: "change"}
        ],
        resFormat: [
          {required: true, message: "文件格式不能为空", trigger: "blur"}
        ],
        resRemake: [
          {required: true, message: "文件说明不能为空", trigger: "blur"}
        ],
        resSize: [
          {required: true, message: "请上传文件", trigger: "blur"}
        ],
        resDownloadCount: [
          {required: true, message: "文件下载次数不能为空", trigger: "blur"}
        ],
      },
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: [],
        fileId: null
      },
    };
  },
  created() {
    this.getList();
  },
  filters: {
    /**
     * 文件大小格式化
     * @param val
     * @returns {string}
     */
    filterType: function (val) {
      if (val === 0) return "0 B"
      var k = 1024;
      var sizes = ['B', 'KB', 'MB', 'GB', 'PB', 'TB', 'EB', 'ZB', 'YB'],
        i = Math.floor(Math.log(val) / Math.log(k));
      return (val / Math.pow(k, i)).toPrecision(3) + "" + sizes[i]

    }
  },
  methods: {
    /** 查询学习文件列表 */
    getList() {
      this.loading = true;
      listResources(this.queryParams).then(response => {
        this.resourcesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        resName: null,
        resType: null,
        resFormat: null,
        resRemake: null,
        resSize: null,
        resDownloadCount: null,
      };
      this.upload.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学习文件";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getResources(id).then(response => {
        this.form = response.data;
        if (response.data.sysFileInfo != null && response.data.sysFileInfo != undefined) {
          this.form.outlineId = response.data.sysFileInfo.fileId;
          let file = {"name": response.data.sysFileInfo.fileName, "url": response.data.sysFileInfo.filePath};
          this.upload.fileList.push(file);
        }
        this.open = true;
        this.title = "修改学习文件";
      });
    },
    /**
     * 审核文件
     */
    handleAudit(state, row) {
      const id = row.id
      console.log(state);
      updateResources({id: id, resState: state}).then(response => {
        this.$modal.msgSuccess("审核成功！");
        this.open = false;
        this.getList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateResources(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addResources(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除学习文件编号为"' + ids + '"的数据项？').then(function () {
        return delResources(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/resources/export', {
        ...this.queryParams
      }, `resources_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
// 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.form.filePath = response.url;
      this.form.resId = response.fileId;
      this.upload.fileId = response.fileId;
      this.form.resFormat = response.fileFormat;
      this.form.resSize = response.fileSize;
      // this.$modal.msgSuccess(response.msg);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制最多选择 1 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    /**
     * 日期格式化
     * @param row
     * @param column
     * @returns {string|null}
     */
    dateFormat(row, column) {
      //方法区
      // 获取单元格数据
      let data = row[column.property]
      if (data == null) {
        return null
      }
      let dt = new Date(data)
      return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate() + ' ' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds()
    },
    /**
     * 文件下载
     */
    // 文件下载处理
    handleDownload(row) {
      let id = row.id;
      getResources(id).then(response => {
        let value = response.data.sysFileInfo.filePath;
        //根据文件路径参数，按斜杠进行分割，取得文件名，这是download函数需要的第三个参数
        let list = value.split("/");
        let fileName = list[list.length - 1];
        this.$message.success("正在下载请稍后...");
        downLoadFile(id).then(data => {
          let url = window.URL.createObjectURL(new Blob([data]));
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", response.data.sysFileInfo.fileName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link); // 下载完成移除元素
          window.URL.revokeObjectURL(url); // 释放掉blob对象
          this.getList();
        })
      });
    },
  }
};
</script>
